package db;
import java.sql.*;
import java.util.*;

public class Connector {
    public static ArrayList<Connection> activeCons = new ArrayList<Connection>();
	public static final String DBNAME="librarydb";
	private static String user="root",passwd="password"; //default user/passwd
	private Connector(){
		Runtime.getRuntime().addShutdownHook(new ShutDownHook());
	}
	
	public static Connection getConnection(String userName, String password){
	  user=userName;
	  passwd=password;
	  return getConnection();
	}
	
	/* Always check if the connection is valid throuth this method.*/
	public static boolean isValidConnection(Connection con){
		try{
		if(con==null) return false;
		if(con.isClosed()){
		    activeCons.remove(con);
		    return false;
	     }
	     return true;
		}catch(SQLException sql){
			return false;
		}
	}
   
	
	public static Connection getConnection() {
	  try{
		//Register the JDBC driver for MySQL.
	      Class.forName("com.mysql.jdbc.Driver");

	      //Define URL of database server for
	      // database named mysql on the localhost
	      // with the default port number 3306.
	      String url =
	            "jdbc:mysql://localhost:3306/"  + DBNAME;

	      //Get a connection to the database for a
	      // user named root with a blank password.
	      // This user is the default administrator
	      // having full privileges to do anything.
	      Connection con =
	                     DriverManager.getConnection(
	                                 url,user, passwd);
	      activeCons.add(con);
	      return con;

	  }catch(Exception e){
		  //we do this so that errors get reported
		  //at the same time, client does have to use annoying try catch
		  throw new DBError (e);
	  }

	}

	public static void closeConnections() {
		// TODO Auto-generated method stub
		for(Connection c:activeCons){
			try{
				c.close();
			}catch(Exception e){
				System.out.println("Could not close connection");
			}
		}
		
	}
}
